import axios, { type AxiosInstance, type AxiosRequestConfig, type AxiosResponse } from 'axios';
import type { ApiResponse } from '@/types/response';
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router';

const instance: AxiosInstance = axios.create({
  // baseURL: 'https://127.0.0.1:8000', // 基础 URL
  timeout: 3000, // 超时时间
  headers: {
    'Content-Type': 'application/json',
  },
});

// 请求拦截器
instance.interceptors.request.use(
  (config) => {
    const authStore = useAuthStore()
    if (authStore.isLoggedIn) {
      config.headers['Authorization'] = `Bearer ${authStore.token}`
    }
    return config
  },
  (error) => Promise.reject(error)
);

// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    const { data } = response;
    if (data.code !== 200) {
      console.error('API Error:', data.message);
      throw new Error(data.message);
    }
    return data.data; // 返回 data 字段
  },
  (error) => {
    const router = useRouter()
    if (error.response && error.response.status === 401) {
      const authStore = useAuthStore()
      authStore.logout()
      const currentPath = router.currentRoute.value.fullPath
      if (currentPath !== '/login') {
        router.push(`/login?redirect=${encodeURIComponent(currentPath)}`)
      }
    }
    return Promise.reject(error);
  }
);

export default instance;
